package com.ruoyi.project.xcx.filter;

import com.ruoyi.project.xcx.user.domain.XcxUser;
import com.ruoyi.project.xcx.util.JWTUtil;
import com.ruoyi.project.xcx.util.TokenUserUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Configuration
@WebFilter(filterName = "tokenFilter",urlPatterns = {"/wx/*"})
@Slf4j
public class TokenFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("token Filter begin");
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        String uri = req.getRequestURI();
        if(uri.endsWith("login")){
            filterChain.doFilter(servletRequest, servletResponse);
        }else{
            String token = req.getHeader("token");
            if(StringUtils.isBlank(token)){
                log.warn("token is null.todo");
                // todo pan 拒绝访问，提示请登陆
                XcxUser user = new XcxUser();
                user.setId(123L);
                TokenUserUtil.putUser(user);
                filterChain.doFilter(servletRequest, servletResponse);
            }else{
                XcxUser user = JWTUtil.getUser(token);
                if(user == null){
                    // todo pan 拒绝访问，提示登陆
                    user = new XcxUser();
                    user.setId(123L);
                    TokenUserUtil.putUser(user);
                }else{
                    TokenUserUtil.putUser(user);
                }
                filterChain.doFilter(servletRequest, servletResponse);
            }
        }
    }

    @Override
    public void destroy() {

    }
}